import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { Team } from '@/types/account';
import { accountService } from '@/services/accountService';

interface TeamState {
  currentTeam: Team | null;
  myTeams: Team[];
  isLoading: boolean;
  setCurrentTeam: (team: Team | null) => void;
  setMyTeams: (teams: Team[]) => void;
  clearTeam: () => void;
  clearMyTeams: () => void;
  fetchMyTeam: () => Promise<void>;
  leaveTeam: (teamId: number) => Promise<boolean>;
}

export const useTeamStore = create<TeamState>()(
  persist(
    (set, get) => ({
      currentTeam: null,
      myTeams: [],
      isLoading: false,
      setCurrentTeam: (team: Team | null) => set({ currentTeam: team }),
      setMyTeams: (teams: Team[]) => set({ myTeams: teams }),
      clearTeam: () => set({ currentTeam: null }),
      clearMyTeams: () => set({ myTeams: [] }),
      
      // 获取用户所属的团队
      fetchMyTeam: async () => {
        set({ isLoading: true });
        try {
          const response = await accountService.getMyTeam();
          if (response.data && Array.isArray(response.data)) {
            set({ myTeams: response.data });
            // 如果有团队，总是选择第一个作为默认团队
            if (response.data.length > 0) {
              set({ currentTeam: response.data[0] });
            } else {
              set({ currentTeam: null });
            }
          } else {
            set({ myTeams: [], currentTeam: null });
          }
        } catch (error) {
          console.error('获取用户团队失败:', error);
          set({ myTeams: [], currentTeam: null });
        } finally {
          set({ isLoading: false });
        }
      },

      // 退出团队
      leaveTeam: async (teamId: number) => {
        try {
          await accountService.leaveTeam(teamId);
          // 从团队列表中移除该团队
          const { myTeams, currentTeam } = get();
          const updatedTeams = myTeams.filter(team => team.id !== teamId);
          set({ myTeams: updatedTeams });
          
          // 如果退出的是当前选中的团队，选择其他团队或清空
          if (currentTeam && currentTeam.id === teamId) {
            if (updatedTeams.length > 0) {
              set({ currentTeam: updatedTeams[0] });
            } else {
              set({ currentTeam: null });
            }
          }
          return true;
        } catch (error) {
          console.error('退出团队失败:', error);
          return false;
        }
      },
    }),
    {
      name: 'team-storage',
      storage: createJSONStorage(() => localStorage),
      partialize: (state) => ({
        currentTeam: state.currentTeam,
        myTeams: state.myTeams,
      }),
    }
  )
); 